﻿using DX;
using DX.Behaviors;
using DX.IO;
using DX.ViewModels;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Threading.Tasks;
using Tools.Plugins.IconConver.Views;

namespace Tools.Plugins.IconConver.ViewModels
{
    [ViewType(typeof(IconViewControl))]
    public partial class IconViewModel : ViewModel
    {

        public IconViewModel(IFileSystemDialog fileSystemDialog, IMessageCenter messageCenter)
        {
            this._fileSystemDialog = fileSystemDialog;
            this._messageCenter = messageCenter;
            iconService = new IconService();
            Title = "转成图标";
        }

        private readonly IFileSystemDialog _fileSystemDialog;
        private readonly IMessageCenter _messageCenter;
        readonly IconService iconService;
        FileEntry _selectdFile;
        protected override Task<bool> OnCanClose()
        {
            return _messageCenter.Confirmation("还没保存", "是否关闭！");
        }

        [CommunityToolkit.Mvvm.Input.RelayCommand]
        private async Task SelectedImage()
        {

            var file = await _fileSystemDialog.OpenSingleFile("All Images|*.jpge;*.png;*.bmp");
            if (file == null) { return; }
            _selectdFile = file;
            if (View is IPicboxBehavior picboxBehavior) picboxBehavior.SetImage(file);


        }
        [CommunityToolkit.Mvvm.Input.RelayCommand]
        private async Task SaveTo()
        {


            if (_selectdFile == null)
            {
                await _messageCenter.Show("未选择图片");
                return;
            }
            var img = Image.FromFile(_selectdFile.FullName);
            var buffer = iconService.ConvertToIcon(img);
            await _fileSystemDialog.OpenSaveAs(FileEntry.Buffer("logo.ico", buffer));
        }
    }

}
